package com.maikang.exammall.util;

import com.mongodb.BasicDBObject;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@Log4j2
@Order(3)//Order用来定义切面执行顺序
public class WebLogAspect {
    //定义日志记录器
    @Pointcut("execution(public  * com.maikang.exammall.api.*.*(..))")
    public void weblog(){}
    @Before("weblog()")
    public void dobefore(JoinPoint joinPoint){
        //由于切面类不能从方法入参注入、所以只能这样获取servlet请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //mongodb保存的基本对象(文档)
        BasicDBObject object = getBasicDBObject(request,joinPoint);
        log.info(object.toString());
    }
    private BasicDBObject getBasicDBObject(HttpServletRequest request,JoinPoint joinPoint){
        BasicDBObject b = new BasicDBObject();
        b.append("RequestURL:",request.getRequestURI().toString());
        b.append("METHOD",request.getMethod());
        b.append("RemoteAddr",request.getRemoteAddr());
        b.append("HEADER",getHeader(request));
        //b.append("CLASS_METHOD",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignat);
        b.append("Args", Arrays.toString(joinPoint.getArgs()));
        return b;
    }
    private Object getHeader(HttpServletRequest request){
        Map<String,String> map  = new HashMap<>();
        Enumeration<String> header = request.getHeaderNames();
        while (header.hasMoreElements()){
            String key = header.nextElement();
            map.put(key,request.getHeader(key));
        }
        return map;
    }
}